<template>
  <el-dialog v-model="visible" :title="dialogTitle" width="800px" @close="handleClose" destroy-on-close>
    <el-transfer v-model="selectedItems" :data="allItems" :titles="['保养项列表', '已配置列表']" :button-texts="['移除', '添加']"
      filterable :filter-method="filterMethod" filter-placeholder="请输入名称或编码">
      <template #default="{ option }">
        <span>{{ option.name }}</span>
        <span class="item-code">({{ option.code }})</span>
      </template>
    </el-transfer>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { UpkeepItemApi } from '@/api/mold/upkeepitem'
import { UpkeepCategoryApi } from '@/api/mold/upkeepcategory'

interface TransferItem {
  key: number
  label: string
  name: string
  code: string
  disabled?: boolean
}

interface Props {
  catId: number
  title: string
}

const props = defineProps<Props>()

// 对话框状态
const visible = ref(false)
const dialogTitle = ref('')
const categoryId = ref(0) // 用于存储传入的catId，避免直接修改prop
const allItems = ref<TransferItem[]>([])
const selectedItems = ref<number[]>([])

// 打开对话框
const open = async (catId: number, title: string) => {
  categoryId.value = catId
  dialogTitle.value = title || `配置保养项 - ID: ${catId}`
  visible.value = true

  // 获取所有保养项
  await getAllUpkeepItems()

  // 获取已配置的保养项
  await getAlreadyConfiguredItems(catId)
}

// 获取所有保养项
const getAllUpkeepItems = async () => {
  try {
    const res = await UpkeepItemApi.getItemAll()
    allItems.value = res.map(item => ({
      key: item.id,
      label: `${item.name} (${item.code})`,
      name: item.name,
      code: item.code
    }))
  } catch (error) {
    ElMessage.error('获取保养项列表失败')
    console.error(error)
  }
}

// 获取已配置的保养项
const getAlreadyConfiguredItems = async (catId: number) => {
  try {
    const res = await UpkeepCategoryApi.getItemsByCatId(catId)
    selectedItems.value = res.map(item => item.itemId)
  } catch (error) {
    ElMessage.error('获取已配置保养项失败')
    console.error(error)
  }
}

// 自定义过滤方法
const filterMethod = (query: string, item: TransferItem) => {
  return item.name.toLowerCase().includes(query.toLowerCase()) ||
    item.code.toLowerCase().includes(query.toLowerCase())
}

// 提交配置
const handleSubmit = async () => {
  try {
    // 先删除所有现有配置
    await UpkeepCategoryApi.deleteByCategoryId(categoryId.value)

    // 如果有选中的项，则批量创建新的关联
    if (selectedItems.value.length > 0) {
      // 构建请求参数
      const saveReqVOs = selectedItems.value.map(itemId => ({
        categoryId: categoryId.value,
        itemId: itemId
      }))

      await UpkeepCategoryApi.batchCreateUpkeepCat2item(saveReqVOs)
    }

    ElMessage.success('配置保存成功')
    visible.value = false
    emit('success')
  } catch (error) {
    ElMessage.error('保存配置失败')
    console.error(error)
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  // 重置数据
  allItems.value = []
  selectedItems.value = []
}

// 定义事件发射器
const emit = defineEmits(['success'])

// 暴露方法
defineExpose({
  open
})
</script>

<style scoped>
.item-code {
  color: #999;
  margin-left: 5px;
}
</style>